package com.lw.service.impl;

import com.lw.entity.ImageTable;
import com.lw.mapper.FileUploadMapper;
import com.lw.service.FileUploadService;
import com.lw.utils.Utils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@Service
public class FileUploadServiceImpl implements FileUploadService {
    //实例化工具类
    Utils utils = new Utils();

    @Resource
    FileUploadMapper fileUploadMapper;

    /**
     * 单图上传实现方法
     */
    @Override
    public int uploadImage(MultipartFile file, HttpServletRequest request) {
        if (utils.checkImage(file)) {
            //获取图片字节流
            try {
                byte[] bytes = file.getBytes();
                String imageName = file.getOriginalFilename();
                //调用dao接口存储图片
                int rep = fileUploadMapper.insertImages(bytes[0], imageName);
                return rep;

            } catch (IOException e) {
                e.printStackTrace();
                return -1;
            }
        }
        return -1;

    }

    /**
     * 多图上传实现方法
     */
    @Override
    public int uploadImages(MultipartFile[] file, HttpServletRequest request) {
        int count = 0;
        for (int i = 0; i < file.length; i++) {
            try {
                byte[] bytes = file[i].getBytes();
                String imageName = file[i].getOriginalFilename();
                //调用dao接口存储图片
                count += fileUploadMapper.insertImages(bytes[0], imageName);
            } catch (IOException e) {
                e.printStackTrace();
                return -1;
            }
        }
        return count;
    }

    /**
     * 根据据图片名称下载图片到本地
     * return imageTable对象
     */
    @Override
    public ImageTable getImage(String imageName) {

        return null;
    }
}
